<template>
  <div class="overtrue">
    <div class="head">

      <div class="score">
        <h1 class="scoreA" @click="netOn">{{scoreA}}</h1>
        <h1 class="mid" @click="soundon">:</h1>
        <h1 class="scoreB">{{scoreB}}</h1>
      </div>

      <div v-if="!net" class="time">
        <h1 v-show="timebtn===1" class="addtime" @click="addTime">+</h1>
        <h1 v-show="timebtn===0||timebtn===1" class="timevalue">{{timevalue}}s</h1>
        <h1 v-show="timebtn===1" class="subtime" @click="subTime">-</h1>
      </div>
      <div v-else class="time">
        <h1 v-show="timebtn===1" class="addtime" @click="netCtr(1)">+</h1>
        <h1 v-show="timebtn===0||timebtn===1" class="timevalue">{{timevalue}}s</h1>
        <h1 v-show="timebtn===1" class="subtime" @click="netCtr(2)">-</h1>
      </div>

    </div>

    <div class="body">
      <div class="checkerboard">
        <div class="chess"></div>
        <div class="lattice_all">
          <div class="lattice_row" v-for="(row,index) in map">
            <div class="lattice" v-for="(col,index) in row"></div>
          </div>
        </div>
      </div>
    </div>

    <div  v-if="!net" class="tall">
      <div class="left" @click="left"></div>
      <div class="run" @click="run"></div>
      <div class="right" @click="right"></div>
    </div>
    <div  v-else class="tall">
      <div class="left" @click="netCtr(3)"></div>
      <div class="run" @click="netCtr(4)"></div>
      <div class="right" @click="netCtr(5)"></div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import axios from "axios";

let map=[//棋盘
    [0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
];
//从服务器获取的操作
let net=ref(false);//联网模式关闭
let fire=1;//进攻时间
let fallnum=0;//落棋参考值
let newData = {// 你要写入文件的新数据
  data: '0,3,0',
};
let getDataTemp;
let timeCtr;
let moveCtr;
let fallCtr;
let timeGap;
let moveGap;
let nethttp='localhost';

let maxW=window.innerHeight*0.615;
let winW=window.innerWidth;
let positionX=3;//棋子初始水平位置
let positionY=0;//棋子初始垂直位置
let attack=1;//当前进攻方
let button_btn=true;//按钮锁
let scoreA=ref(0);//a方得分
let scoreB=ref(0);//a方得分
let drawnGame=0;//是否和局
//计时器参数
let timevalue=ref(0);//当前时间
let timetemp=0;//进攻时间
let timeoff=1;//计时器关闭
let timebtn=ref(1);//计时器按钮显示
//音效
let soundbtn=false;
const audio_chess_fall = new Audio("sound/chess_fall.mp3");
const audio_victory=new Audio('sound/victory.mp3');
const audio_chess_move=new Audio('sound/chess_move.mp3')
audio_chess_move.volume = 0.4;
const audio_time=new Audio('sound/time.mp3')
audio_time.volume=0.4;
onMounted(() => {
  document.querySelector('.chess').classList.add('red');
  document.querySelector('.chess').style.transform="translateX(300%)";
  //监听键盘事件
  window.addEventListener('keydown', handleKeyDown);
  if(winW>500){
    document.getElementsByClassName('overtrue')[0].style.maxWidth= `${maxW}px`;
    soundbtn=true;//电脑端自动开启音效
  }
});

//打开联网功能
function netOn(){
  console.log("开启联网功能")
  net.value=!net.value;
  console.log("初始化对局")
  upData()//初始化对局

  //开始监听服务器数据
  console.log("获取服务器数据")
  const getdatatimer1=setInterval(function(){
    //轮询获取数据
    axios.get(`http://${nethttp}:3000/file`)
      .then(res=>{
        getDataTemp=res.data;
        //如果数据与本地不相等,则根据服务器数据进行调整
        if(fire===0){
          console.log("我方优先攻击")
          clearInterval(getdatatimer1);//关闭数据获取
        }
        else if(newData.data!==getDataTemp){
          //截取对应数据
          timeCtr=parseInt(getDataTemp.split(',')[0]);
          moveCtr=parseInt(getDataTemp.split(',')[1]);
          fallCtr=parseInt(getDataTemp.split(',')[2]);
          //如是落棋数据不相等，表示敌方已落棋
          if(fallnum!==fallCtr){
            console.log(fallnum,fallCtr,"敌方优先进攻");
            clearInterval(getdatatimer1);//关闭数据获取
            fallnum++;//落棋次数+1
            run();//进攻完毕
            fire=1;//切换我方进攻
            newData.data=`${timetemp},3,${fallnum}`;
          }//其他数据则进行调整
          else if(timeCtr!==timetemp){
            console.log(timeCtr,timetemp,"敌方调整时间中");
            timeGap=timetemp-timeCtr;
            if(timeGap<0){
              addTime();
            }else if(timeGap>0){
              subTime();
            }
            newData.data=`${timetemp},${positionX},${fallnum}`;
          }else if(moveCtr!==positionX){
            console.log("敌方开始移动");
            moveGap=positionX-moveCtr;
            if(moveGap<0){
              right();
            }else if(moveGap>0){
              left();
            }
            newData.data=`${timetemp},${positionX},${fallnum}`;
          }
        }
      })
  },10);
}
function netCtr(fun){
  if(fire) {
    switch (fun) {
      case 1:
        console.log("时间+1")
        addTime();
        upData();
        break;
      case 2:
        console.log("时间-1")
        subTime();
        upData();
        break;
      case 3:
        console.log("左移")
        left();
        upData();
        break;
      case 5:
        console.log("右移")
        right();
        upData();
        break;
      case 4:
        console.log("落棋")
        fallnum++;
        run();
        upData();
        fire = 0;
        setTimeout(function () {
          console.log("进攻已发起，进入观战时间")
          //获取对方攻击
          const getdatatimer = setInterval(function () {
            axios.get(`http://${nethttp}:3000/file`)
              .then(res=>{
                getDataTemp=res.data;
                if (getDataTemp !== newData.data) {
                  console.log(getDataTemp,newData.data,"敌方进攻")
                  timeCtr = parseInt(getDataTemp.split(',')[0]);
                  moveCtr = parseInt(getDataTemp.split(',')[1]);
                  fallCtr = parseInt(getDataTemp.split(',')[2]);
                  if(fallCtr!==fallnum){
                    console.log(fallCtr,fallnum,"敌方落棋")
                    clearInterval(getdatatimer);
                    fallnum++;
                    run();
                    fire=1;
                  }else if (timeCtr !== timetemp) {
                    console.log(timeCtr,timetemp,"敌方调整时间")
                    timeGap = timetemp - timeCtr;
                    if (timeGap < 0) {
                      addTime();
                    } else if (timeGap > 0) {
                      subTime();
                    }
                  }else if (moveCtr!== positionX) {
                    console.log(moveCtr,positionX,"敌方调整位置")
                    moveGap = positionX - moveCtr;
                    if (moveGap < 0) {
                      right();
                    } else if (moveGap > 0) {
                      left();
                    }
                  }
                }
              })
          }, 10);
        }, 350)
        break;
    }
  }
}
function upData(){
  newData.data=`${timetemp},${positionX},${fallnum}`;
  getDataTemp=newData.data;
  axios.post(`http://${nethttp}:3000/file`,newData)
}

function handleKeyDown(event){
  if(!net.value) {
    switch (event.key) {
      case 'A':
      case 'a':
      case 'ArrowLeft':
        left();
        break;
      case 'D':
      case 'd':
      case 'ArrowRight':
        right();
        break;
      case 's':
      case 'S':
      case 'ArrowDown':
      case 'Enter':
      case ' ':
        run();
        break;
      case '=':
      case '+':
        addTime();
        break;
      case '-':
      case '_':
        subTime();
        break;
    }
  }else{
    switch (event.key) {
      case 'A':
      case 'a':
      case 'ArrowLeft':
        netCtr(3);
        break;
      case 'D':
      case 'd':
      case 'ArrowRight':
        netCtr(5);
        break;
      case 's':
      case 'S':
      case 'ArrowDown':
      case 'Enter':
      case ' ':
        netCtr(4);
        break;
      case '=':
      case '+':
        netCtr(1);
        break;
      case '-':
      case '_':
        netCtr(2);
        break;
    }
  }
}
function soundon(){
  soundbtn=!soundbtn;
}
function addTime(){
  if(soundbtn){
    audio_time.currentTime = 0;
    audio_time.play();
  }
  timevalue.value++;
  timetemp++;
}
function subTime(){
  if(soundbtn){
    audio_time.currentTime = 0;
    audio_time.play();
  }
  if(timevalue.value>0){
    timevalue.value--;
    timetemp--;
  }
}


function left(){
  if(positionX>0&&button_btn){
    if(soundbtn){
      audio_chess_move.play();
    }
    document.querySelector('.chess').classList.add('chess-move');
    positionX--;
    document.querySelector('.chess').style.transform=`translateX(${positionX*100}%)`;
  }
}

function startTimer() {
  let num=0;
  let time1=setInterval(function (){
    num++;
    if(timevalue.value<=1){
      if(num===5||num===10) {
        if(soundbtn){
          audio_time.currentTime = 0;
          audio_time.play();
        }
      }
    }
    //到达一秒后运行
    if(num===10){
      num=0;
      if(timevalue.value>1){
        if(soundbtn){
          audio_time.play();
        }
      }
      timevalue.value--;
      //若时间到了，直接下棋
      if(timevalue.value<0){
        timevalue.value++;
        run();
      }
    }
    //计时器关闭
    if(timeoff!==0){
      clearInterval(time1)
    }
  },100)
}
function run(){
  if(timetemp===0){//如果没有设置对局时间，则不显示时间
    timebtn.value=2;
  }else{
    timebtn.value=0;//关闭时间控制
    timeoff=1;//上一个计时器关闭
    setTimeout(function (){
      timeoff=0;//计时器关闭取消
      timevalue.value=timetemp;
      startTimer();//开始计时
    },350)
  }
  if(soundbtn){
    audio_chess_move.play();
  }
  if(button_btn) {
    document.querySelector('.chess').classList.add('chess-move');
    if (map[0][positionX] === 0) {
      button_btn=false;
      for (let i = 0; i < map.length; i++) {
        if (map[i][positionX] === 0) {
          positionY++;
        } else {
          break;
        }
      }
      map[positionY - 1][positionX] = attack;
      document.querySelector('.chess').style.transform = `translate(${positionX * 100}%,${positionY * 100}%)`;
      if(rule()===0) {
        //未出现终局
        if(soundbtn){
          setTimeout(function (){
            audio_chess_fall.play();
          },270);
        }
        setTimeout(function () {
          if (attack === 1) {
            attack = 2;
            document.querySelector('.chess').classList.add('blue');
            document.querySelector('.chess').classList.remove('red');
            document.querySelector('.lattice_all')
                .children[positionY - 1]
                .children[positionX].classList.add('lattice_red')
          } else {
            attack = 1;
            document.querySelector('.chess').classList.add('red');
            document.querySelector('.chess').classList.remove('blue');
            document.querySelector('.lattice_all')
                .children[positionY - 1]
                .children[positionX].classList.add('lattice_blue')
          }
          positionX = 3;
          positionY = 0;
          document.querySelector('.chess').classList.remove('chess-move');
          document.querySelector('.chess').style.transform = `translate(${positionX * 100}%,${positionY * 100}%)`;
          document.querySelector('.chess').classList.add('chess-small');
          setTimeout(function(){
            button_btn=true;
          },100);
        }, 350);
      }else if(rule()===1){
        //出现终局
        if(soundbtn) {
          if (drawnGame === 0) {
            setTimeout(function () {
              audio_victory.play();
            }, 270);
          } else {
            setTimeout(function () {
              audio_chess_move.play();
            }, 270);
          }
        }
        setTimeout(function () {
          if (attack === 1) {
            if(drawnGame===0)scoreA.value++;
            attack = 2;
            document.querySelector('.chess').classList.add('blue');
            document.querySelector('.chess').classList.remove('red');
          } else {
            if(drawnGame===0)scoreB.value++;
            attack = 1;
            document.querySelector('.chess').classList.add('red');
            document.querySelector('.chess').classList.remove('blue');
          }
          positionX = 3;
          positionY = 0;
          document.querySelector('.chess').classList.remove('chess-move');
          document.querySelector('.chess').style.transform = `translate(${positionX * 100}%,${positionY * 100}%)`;
          document.querySelector('.chess').classList.add('chess-small');
          for(let i=0;i<map.length;i++){
            for(let j=0;j<map[0].length;j++){
              document.querySelector('.lattice_all')
                  .children[i]
                  .children[j].classList.remove('lattice_blue')
              document.querySelector('.lattice_all')
                  .children[i]
                  .children[j].classList.remove('lattice_red')
              map[i][j]=0;
            }
          }
          setTimeout(function(){
            button_btn=true;
          },100);
          timeoff=1;//关闭计时器
          timebtn.value=1;//打开时间控制
        },1000);
      }
    }
  }
}

//规则判断
function rule(){
  //全部位置都下满了棋
  let drawn=true;
  for(let i=0;i<map.length;i++){
    for(let j=0;j<map[0].length;j++){
      if(map[i][j]===0){
        drawn=false;
      }
    }
  }
  if(drawn){
    drawnGame=1;//和局
    return 1;
  }

  let conChessNum=0;//连续的棋子数
  //横向判断
  for(let i=0;i<map[0].length;i++){
    if(map[positionY - 1][i]===map[positionY - 1][positionX]){
      conChessNum++;
    }else{
      conChessNum=0;
    }
    if(conChessNum===4){
      return 1
    }
  }
  //竖直判断
  conChessNum=0;
  for(let i=0;i<map.length;i++){
    if(map[i][positionX]===map[positionY - 1][positionX]){
      conChessNum++;
    }else{
      conChessNum=0;
    }
    if(conChessNum===4){
      return 1
    }
  }
  //捺判断
  conChessNum=0;
  let ytemp=0,xtemp=0;
  for(let i=positionY - 1,j=positionX;i<map.length&&j<map[0].length;i++,j++){
    ytemp=i;
    xtemp=j;
  }
  for(let i=ytemp,j=xtemp;i>=0&&j>=0;i--,j--){
    if(map[i][j]===map[positionY - 1][positionX]){
      conChessNum++;
    }else{
      conChessNum=0;
    }
    if(conChessNum===4){
      return 1
    }
  }
  //撇判断
  conChessNum=0;
  for(let i=positionY - 1,j=positionX;i<map.length&&j<map[0].length;i++,j--){
    ytemp=i;
    xtemp=j;
  }
  for(let i=ytemp,j=xtemp;i>=0&&j>=0;i--,j++){
    if(map[i][j]===map[positionY - 1][positionX]){
      conChessNum++;
    }else{
      conChessNum=0;
    }
    if(conChessNum===4){
      return 1
    }
  }
  return 0;
}
function right(){
  if(positionX<6&&button_btn){
    if(soundbtn){
      audio_chess_move.play();
    }
    document.querySelector('.chess').classList.add('chess-move');
    positionX++;
    document.querySelector('.chess').style.transform=`translateX(${positionX*100}%)`;
  }
}
</script>
<style>
.overtrue {
  width: 100%;
  height: 100%;
  margin: auto;
  background-image: url("/public/wallpaper.jpg") ;
  background-size: cover;
}
.head{
  height: 22%;
  position: relative;
}
.body{
  height: 60%;
  margin-bottom: 10%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.tall{
  height: 11%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 7px solid saddlebrown;
  background-color:  rgb(250, 235, 215);
}
.checkerboard{
  width: 95%;
  background-color: rgb(234, 207, 156);
  position: relative;
  padding: 2%;
  border-radius: 2%;
}
.lattice_all{
  position: relative;
  border: 4px solid #5d260c;
  border-bottom-left-radius: 3%;
  border-bottom-right-radius: 3%;
}
.lattice_row{
  display: flex;
}
.lattice {
  width: 14.2857%;
  aspect-ratio: 1/1; /* 设置宽高比为 1:1 */
  background: radial-gradient(100% 100% at 50% 50%, rgba(205, 133, 63, 0) 39%, rgb(138, 66, 14) 40%);
}
.lattice_red{
  width: 14.2857%;
  aspect-ratio: 1/1; /* 设置宽高比为 1:1 */
  background: radial-gradient(100% 100% at 50% 50%, darkred 39%, rgba(138, 66, 14, 1) 40%);
}
.lattice_blue{
  width: 14.2857%;
  aspect-ratio: 1/1; /* 设置宽高比为 1:1 */
  background: radial-gradient(100% 100% at 50% 50%, darkblue 39%, rgba(138, 66, 14, 1) 40%);
}
.lattice_row:nth-child(6)>.lattice:nth-child(1){
  border-bottom-left-radius: 8%;
}
.lattice_row:nth-child(6)>.lattice:nth-child(7){
  border-bottom-right-radius: 8%;
}
.chess{
  position: relative;
  width: 14.2857%;
  aspect-ratio: 1/1; /* 设置宽高比为 1:1 */
  clip-path: circle(44% at 50% 50%);
  transform: translateY(0%);
}
.chess-small{
  transform: scale(0.5);
}
.chess-move{
  transition: transform 0.35s ease;
  transform: scale(2);
}
.red{
  background-color: darkred;
}
.blue{
  background-color: darkblue;
}

.left{
  width: 21%;
  aspect-ratio: 1/0.7;
  background-color: rgb(103, 6, 6);
  clip-path: polygon(0% 50%, 100% 0%, 100% 100%);
  cursor: pointer;

}
.run{
  margin-left: 12%;
  margin-right: 12%;
  width: 15%;
  aspect-ratio: 1/1;
  background-color: rgb(103, 6, 6);
  border-radius: 10%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
  cursor: pointer;

}
.right{
  width: 21%;
  aspect-ratio: 1/0.7;
  background-color: rgb(103, 6, 6);
  clip-path: polygon(0% 0%, 100% 50%, 0% 100%);
  cursor: pointer;
}
.score{
  position: absolute;
  width: 100%;
  aspect-ratio: 1/0.15;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.time{
  position: absolute;
  width: 100%;
  aspect-ratio: 1/0.1;
  top: 75%;
  left: 50%;
  transform: translate(-50%, -50%);

  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.scoreA,.scoreB,.mid {
  font-size: 300%;
  color:rgb(237,215,189)
}
.mid{
  margin-left: 3%;
  margin-right: 3%;
  margin-top: 6%;
}
.addtime,.subtime,.timevalue {
  color:rgb(237,215,189)
}
.addtime, .subtime{
  cursor: pointer;
}
.timevalue{
  margin-left: 3%;
  margin-right: 3%;
  margin-top: 5%;
}
</style>
